package com.shwread.android.qysw.activity;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

import com.GlideUtil;
import com.TrainActionHelp;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.shwread.android.qysw10000000.R;
import com.shwread.android.ui.curstom.photoview.HackyViewPager;
import com.shwread.android.ui.curstom.photoview.PhotoViewAttacher;
import com.shwread.android.ui.curstom.photoview.PhotoViewAttacher.OnViewTapListener;

import org.geometerplus.android.util.QyreaderPerferencesUtil;

import logic.bean.TrainExamCoursewareDetailBean;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.util.ScreenUtil;


/***
 * 培训相关 课件阅读
 */
public class CoursewareReadActivity extends BaseBusinessActivity implements OnClickListener, OnViewTapListener {
    private TrainExamCoursewareDetailBean file;
    private boolean showInfo = true;
    private ImageView ivTitleBack;
    private TextView tvTitle, tvGotoTest, tvLongIntro, tvName, tvTeacher, tvSchool;

    private View topLayout, bottomLayout;
    private HackyViewPager viewPager;
    private SparseArray<View> views;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.couresewware_read_view);

        if (getIntent().hasExtra("detail")) {
            file = (TrainExamCoursewareDetailBean) getIntent().getSerializableExtra("detail");
        } else {
            finish();
        }
        findViews();
        setListeners();
        initData();
        initAnimation();
    }

    @Override
    public Handler getUIHandler() {
        return null;
    }

    private class MyPagerAdapter extends PagerAdapter {
        PhotoViewAttacher attacher;

        @Override
        public int getCount() {
            return file.getPage();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = views.get(position);
            if (view == null) {
                view = LayoutInflater.from(CoursewareReadActivity.this).inflate(R.layout.cloudread_item, container, false);
                final ImageView img = (ImageView) view.findViewById(R.id.cloudread_item_img);
                final ImageView ivLoading = (ImageView) view.findViewById(R.id.cloudread_item_loading_img);
                final View failLayout = view.findViewById(R.id.cloudread_item_fail_layout);
                final String url = appendImageUrl(file.getUrl(), position + 1);
                attacher = new PhotoViewAttacher(img);
                attacher.setOnViewTapListener(CoursewareReadActivity.this);
                failLayout.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        loading(img, ivLoading, failLayout, url, attacher);
                    }
                });
                loading(img, ivLoading, failLayout, url, attacher);
                views.put(position, view);
            }
            if (view.getParent() != null) {
                container.removeView(view);
            }
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }

    private void loading(final ImageView img, final ImageView loading, final View fail, String url, final PhotoViewAttacher attacher) {
        img.setVisibility(View.GONE);
        fail.setVisibility(View.GONE);
        loading.setVisibility(View.VISIBLE);
        final AnimationDrawable drawable = (AnimationDrawable) loading.getBackground();
        if (drawable != null) drawable.start();

        GlideUtil.loadTrain(CoursewareReadActivity.this, url, img, new RequestListener<String, GlideDrawable>() {
            @Override
            public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
//				Utils.showToast(CoursewareReadActivity.this, "加载失败");
                img.setVisibility(View.GONE);
                loading.setVisibility(View.GONE);
                fail.setVisibility(View.VISIBLE);
                return false;
            }

            //这个用于监听图片是否加载完成
            @Override
            public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
//               Toast.makeText(getApplicationContext(), "图片加载完成", Toast.LENGTH_SHORT).show();
                if (drawable != null) drawable.stop();
                img.setVisibility(View.VISIBLE);
                loading.setVisibility(View.GONE);
                attacher.update();
                return false;
            }
        });
    }

    private class PagerChangeListener implements OnPageChangeListener {
        @Override
        public void onPageScrollStateChanged(int state) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int position) {
            final ImageView img = (ImageView) views.get(position).findViewById(R.id.cloudread_item_img);
            img.setScaleType(ScaleType.FIT_XY);
            PhotoViewAttacher attacher = new PhotoViewAttacher(img);
            tvTitle.setText(getTitle(position + 1, file.getPage()));
            attacher.setOnViewTapListener(CoursewareReadActivity.this);
            attacher.update();
        }
    }

    private String getTitle(int position, int pages) {
        return String.valueOf(position) + "/" + pages + "页";
    }

    private String appendImageUrl(String url, int page) {
        return url + "?c=1&w=" + ScreenUtil.screenWidth + "&h=" + ScreenUtil.screenHeight + "&p=" + page;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void initData() {
        views = new SparseArray<>();
        showInfo = true;
        tvTitle.setText(getTitle(1, file.getPage()));
        tvName.setText(file.getName());
        tvLongIntro.setText(String.format("简介:%s", file.getShortIntro()));
        tvTeacher.setText(String.format("讲师:%s", file.getLecturerName()));
        tvSchool.setText(String.format("学校:%s", file.getSchool()));
        viewPager.addOnPageChangeListener(new PagerChangeListener());
        MyPagerAdapter pagerAdapter = new MyPagerAdapter();
        viewPager.setAdapter(pagerAdapter);
    }

    private void findViews() {
        ivTitleBack = (ImageView) findViewById(R.id.coursewareread_title_back);
        tvTitle = (TextView) findViewById(R.id.coursewareread_title_name);
        tvGotoTest = (TextView) findViewById(R.id.coursewareread_title_gototest);
        tvLongIntro = (TextView) findViewById(R.id.coursewareread_bottom_long_intro);
        viewPager = (HackyViewPager) findViewById(R.id.coursewareread_vp);
        tvName = (TextView) findViewById(R.id.coursewareread_bottom_title);
        tvTeacher = (TextView) findViewById(R.id.coursewareread_bottom_author);
        tvSchool = (TextView) findViewById(R.id.coursewareread_bottom_school);
        topLayout = findViewById(R.id.coursewareread_top_layout);
        bottomLayout = findViewById(R.id.coursewareread_bottom_layout);
        if (file.getHasExam().equals("y")) {
            tvGotoTest.setVisibility(View.VISIBLE);
        } else tvGotoTest.setVisibility(View.GONE);
    }

    private void setListeners() {
        ivTitleBack.setOnClickListener(this);
        viewPager.setOnClickListener(this);
        tvGotoTest.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.coursewareread_title_back:
                finish();
                break;
            case R.id.coursewareread_title_gototest:
                gotoTest();
                break;
        }
    }

    private void gotoTest() {
        String cid = QyreaderPerferencesUtil.getInstance(this, Const.phone_number).getTrainIndexCid();
        Intent intent = new Intent(this, TrainExamCommonWebActivity.class);
        intent.putExtra(DefaultConsts.title_s, "评测");
        intent.putExtra(DefaultConsts.req_url_s, TrainActionHelp.getUrl() + "toTrainExamQuestion.do?cid=" + cid + "&trainId=" + file.getChapterId() + "&evaluateType=" + file.getEvalueteType());
        startActivity(intent);
    }

    private TranslateAnimation mShowTopAnimation;
    private TranslateAnimation mHideTopAnimation;
    private TranslateAnimation mShowBottomAnimation;
    private TranslateAnimation mHideBottomAnimation;

    private void initAnimation() {
        // 从自已-1倍的位置(屏幕顶部)移到自己原来的位置
        mShowTopAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
        mHideTopAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, -1.0f);
        mShowTopAnimation.setDuration(500);
        mHideTopAnimation.setDuration(500);

        // 从自已1倍的位置(屏幕底部)移到自己原来的位置
        mShowBottomAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
        mHideBottomAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 1.0f);
        mShowBottomAnimation.setDuration(500);
        mHideBottomAnimation.setDuration(500);
    }

    private void updateView() {
        showInfo = !showInfo;
        if (showInfo) {
            topLayout.startAnimation(mShowTopAnimation);
            bottomLayout.startAnimation(mShowBottomAnimation);
            topLayout.setVisibility(View.VISIBLE);
            bottomLayout.setVisibility(View.VISIBLE);
        } else {
            topLayout.startAnimation(mHideTopAnimation);
            bottomLayout.startAnimation(mHideBottomAnimation);
            topLayout.setVisibility(View.GONE);
            bottomLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void onViewTap(View view, float x, float y) {
        updateView();
    }
}
